package claybird.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import claybird.dom.Handicap;
import claybird.dom.Person;
import claybird.dom.Result;
@Repository
@Transactional
@SuppressWarnings("unchecked")
public class PersonneDao extends BaseRepository<Person>{
	@Autowired ResultDao resultDao;
	@Autowired HandicapDao handicapDao;
	 public  List<Person> getAllPersonne(){
	        return em.createQuery("select a from Person a order by a.name,a.forName").getResultList();
	    }
	 
	 public void addPersonne(Person pers){
		 this.persist(pers);
	 }

	public List<Person> getListByIds(List<Long> shooterList) {
		List<Person> listToSort = em.createQuery("select p from Person p  where p.id in :listId").setParameter("listId", shooterList).getResultList();
		return listToSort;
	}


	public List<Person> getAllPersonneWithoutGuest() {
		 return em.createQuery("select a from Person a where a.guest =false order by a.name,a.forName").getResultList();

	}

	public boolean isFirst(Person person, short year) {
		Integer tot = (Integer)em.createQuery("select min(h.finalRanking) from Handicap h " +
				" where h.year=:year and h.categorie = :categorie and h.finalRanking>0 and h.person.guest = false ")
				.setParameter("categorie", person.getLastHandicap(year).getCategorie())
				.setParameter("year", year)
				.getSingleResult();
		List<Person> listPerson = em.createQuery("select h.person from Handicap h " +
				" where h.year=:year and h.categorie = :categorie and h.finalRanking =:tot and h.person.guest = false " +
				" order by h.finalRanking")
				.setParameter("categorie", person.getLastHandicap(year).getCategorie())
				.setParameter("tot", tot)
				.setParameter("year", year).getResultList();
		
		for(Person pers : listPerson){
			if (pers.equals(person)){
				return true;
			}
		}
		return false;
	}


	
}
